//
//  ModifyPayPasswordController.m
//  YaoHeAPP
//
//  Created by xyh on 16/5/23.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ModifyPayPasswordController.h"
#import "Masonry.h"
#import "TongYong.h"
#import "Controller.h"

@interface ModifyPayPasswordController ()<UITextFieldDelegate>
{

    NSArray *labelarray;
    NSString *dangqianmima;
    NSString *xinmima;
    NSString *querenmima;
    NSString *yanzhengma;
    
    CGFloat k_keyboard_offsetY;
    CGFloat k_keyboardHeight;
    NSString *remobile;

    
    NSTimer *timer;
    
    UIButton * button;
    
    
    int timeNum;
}
@end

@implementation ModifyPayPasswordController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ModifyPayPasswordController"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ModifyPayPasswordController"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}


- (void)viewDidDisappear:(BOOL)animated
{
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden=YES;
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"更改支付密码";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    
    labelarray=@[@"手机号:",@"验证码:",@"当前支付密码:",@"新支付密码:",@"确认支付密码:"];
    
    UIView *bigview=[[UIView alloc]initWithFrame:CGRectMake(0, 20+60, SCREEN_WIDTH, 62*labelarray.count)];
    bigview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bigview];
    
    remobile=[NSString  stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kREGMOBILE]] ;
    
    
    for (int i=0; i<labelarray.count; i++) {
        
        UILabel *namela=[[UILabel alloc]init];
        namela.text=labelarray[i];
        namela.font=[UIFont systemFontOfSize:15];
        namela.textColor=[UIColor blackColor];
        namela.frame=CGRectMake(20,20+(22+20+20)*i, 100, 22);
        namela.textAlignment=NSTextAlignmentLeft;
        [bigview addSubview:namela];

        UIImageView *line=[[UIImageView alloc]init];
        line.backgroundColor=[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0  alpha:1];
        line.frame=CGRectMake(0, 20+22+19.5+(22+19.5+20)*i, SCREEN_WIDTH, 0.5);
        [bigview addSubview:line];
        

        
        UITextField *password=[[UITextField alloc]init];
        password.frame=CGRectMake(130, 10+(42+10+10)*i, SCREEN_WIDTH-100-50, 42);
        password.borderStyle=UITextBorderStyleNone;
        password.tag=100+i;
        password.clearButtonMode=UITextFieldViewModeWhileEditing;
        password.secureTextEntry=YES;
        password.font=[UIFont systemFontOfSize:14];
        password.delegate=self;
        [password addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
        [password addTarget:self action:@selector(disMiss) forControlEvents:UIControlEventEditingDidEndOnExit];
        [bigview addSubview:password];
        
        if (i==0) {
            password.hidden=YES;
            UILabel *iphonela=[[UILabel alloc]init];
            iphonela.text=remobile;
            iphonela.font=[UIFont systemFontOfSize:15];
            iphonela.textColor=[UIColor blackColor];
            iphonela.frame=CGRectMake(100,20, 120, 22);
            iphonela.textAlignment=NSTextAlignmentLeft;
            [bigview addSubview:iphonela];
            
            
            //获取验证码的按钮
            button=[UIButton buttonWithType:UIButtonTypeCustom];
            button.frame=CGRectMake(SCREEN_WIDTH-20-90,15, 90, 30);
            button.layer.borderWidth=2;
            button.titleLabel.font=[UIFont systemFontOfSize:14];
            button.layer.borderColor=[UIColor redColor].CGColor;
            [button setTitle:@"发送验证码" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(sendValidation) forControlEvents:UIControlEventTouchUpInside];
            [bigview addSubview:button];
            
            
        }else if (i==1){
            password.secureTextEntry=NO;
            password.placeholder=@"请输入验证码";
            password.frame=CGRectMake(100, 10+(42+10+10)*i, SCREEN_WIDTH-100-50, 42);
            
        }else if (i==2){
            password.placeholder=@"请输入当前支付密码";
            
        }else if (i==3){
            password.placeholder=@"请输入新的支付密码";
            
        }else if (i==4){
            password.placeholder=@"请确认支付密码";
            
        }

        
        
    }
    
    
    
    UIButton *surebut=[[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-248)/2,62*labelarray.count+60+20+20, 248, 40)];
    surebut.backgroundColor=[UIColor colorWithRed:20.f/255.f green:163.f/255.f blue:246.f/255.f alpha:1];
    [surebut setTitle:@"确认提交" forState:UIControlStateNormal];
    surebut.titleLabel.font=[UIFont systemFontOfSize:16];
    [surebut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [surebut addTarget:self action:@selector(surebutAction) forControlEvents:UIControlEventTouchUpInside];
    surebut.layer.masksToBounds=YES;
    surebut.layer.cornerRadius=20;
    [self.view addSubview:surebut];

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
}

#pragma mark -----------------监控键盘--------------------------
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    k_keyboard_offsetY = keyboardRect.origin.y-8;
    k_keyboardHeight = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.view.frame = CGRectMake(0, -120, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }];
    
}

- (void)keyboardWillHide:(NSNotification *)notification{
    
    [UIView animateWithDuration:0.25 animations:^{
        
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    //    [UIView animateWithDuration:0.25 animations:^{
    //        self.view.frame=CGRectMake(0, -50, self.view.frame.size.width, self.view.frame.size.height);
    //    }];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSInteger tagnum=textField.tag;
    if (tagnum==102) {
        dangqianmima=textField.text;
    }else if(tagnum==103){
        xinmima=textField.text;
    }else if(tagnum==104){
        querenmima=textField.text;
    }else if(tagnum==101){
        yanzhengma=textField.text;
    }
    
    
    
    //    [UIView animateWithDuration:0.25 animations:^{
    //        self.view.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //    }];
}
-(void)textFieldDidChanged:(UITextField *)textField
{
    NSInteger tagnum=textField.tag;
    if (tagnum==102) {
        dangqianmima=textField.text;
    }else if(tagnum==103){
        xinmima=textField.text;
    }else if(tagnum==104){
        querenmima=textField.text;
    }else if(tagnum==101){
        yanzhengma=textField.text;
    }
    
    
}

//普通字符串转换为十六进制的。
-(NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}



//键盘弹下
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

//发送验证码
-(void)sendValidation
{
    
    
    NSDictionary*dic=@{@"member_id":remobile};

    [Controller requestWithURL:PostSendMobileCode jsondic:dic finishBlock:^(ClassData *clasData) {
        if ([clasData.number integerValue]==0) {
            timeNum=[NSString stringWithFormat:@"%@",clasData.data].intValue;
            //将其注销重新开始
            if (timer.isValid) {
                [timer invalidate];
            }
            timer=nil;
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
            
        }
        else{
            ALERTSHOW(clasData.message);
        }
    }];

}

-(void)refreshLessTime
{
    timeNum=timeNum-1;
    if (timeNum==0) {
        
        //将其注销重新开始
        if (timer.isValid) {
            [timer invalidate];
        }
        
        timer=nil;
        [button setTitle:@"重新发送" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        button.layer.borderColor=[UIColor redColor].CGColor;
        
    }else{
    
        NSString *sting=[NSString   stringWithFormat:@"剩余 %ds",timeNum];
        
        [button setTitle:sting forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        button.layer.borderColor=[UIColor grayColor].CGColor;

    
    }
    
    


}


//确认提交
-(void)surebutAction
{
    //先判断两个是否为空
    if ([TongYong isBlankObjectAndStr:dangqianmima]) {
        ALERTSHOW(@"当前密码不能为空");
    }else{
        
        if ([TongYong isBlankObjectAndStr:querenmima]) {
            ALERTSHOW(@"请确认密码");
        }else{
            
            if (![xinmima isEqualToString:querenmima]) {
                
                ALERTSHOW(@"您两次输入的密码不同，请核对！");
            }else{
                
                //证明可以提交
                
                NSMutableDictionary *dicd=[[NSMutableDictionary alloc]init];
                
                NSString *dangqianmimaString=[self hexStringFromString:dangqianmima];
                
                [dicd setValue:dangqianmimaString forKey:@"old_pwd"];
                
                NSString *NewmimaString=[self hexStringFromString:xinmima];
                
                [dicd setValue:NewmimaString forKey:@"new_pwd"];
                
                [dicd setValue:yanzhengma forKey:@"check_code"];
                
                [Controller requestWithURL:PostChangePayPwd jsondic:dicd finishBlock:^(ClassData* data) {
                    
                    if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
                    {
                        ALERTSHOW(@"修改成功");
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        
                        ALERTSHOW(data.message);
                        
                    }
                    
                    [MobClick event:@"modifyPaymentPassword"];
                    
                }];
                
            }
            
            
        }
    }


}

-(void)disMiss
{
    return;
}




-(void)backLogin
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end
